import { useState, useRef, useCallback } from 'react'

export default function useThrottle(fn: () => void, delay = 500) {
  const [flag, setFlag] = useState(true)

  return () => {
    let Timer: any = null
    // console.log('hook挂载');
    clearTimeout(Timer)
    if (flag) {
      setFlag(false)
      Timer = setTimeout(() => {
        fn()
        setFlag(true)
      }, delay)
    }
  }
}

//data 默认值， delay 间隔时间 ，leading首次是否触发 ，trainling最后一次是否触发
export function useThro(
  param: any,
  config = { delay: 1000, leading: false, trailing: true },
) {
  const [data, setData] = useState(param)
  //缓存上次执行的setstate方法和计时器
  const setting = useRef({ prevTime: 0, timer: null }).current
  //清除计时器
  const clearTimer = useCallback(() => {
    if (setting.timer) {
      clearTimeout(setting.timer)
      setting.timer = null
    }
  }, [setting])
  //修改上次执行setState的时间并修改state
  const applyFun = useCallback(
    (args, now = 0) => {
      setting.prevTime = now
      setData(args)
    },
    [setting],
  )
  // 返回给用户的方法，注册后永不改变
  const throttle = useRef(args => {
    //获取当前时间
    let now = Date.now()
    //当第一次触发且首次不触发时
    if (!setting.prevTime && !config.leading) {
      setting.prevTime = now
    }
    //距离下次触发的时间
    let remaining = config.delay - (now - setting.prevTime)
    //清除计时器
    clearTimer()
    // 差值小于等于零则立即执行
    if (remaining <= 0) {
      console.log(args, now)
      applyFun(args, now)
    }
    //如果最后一次触发
    if (config.trailing) {
      setting.timer = setTimeout(() => {
        applyFun(args)
        //调用结束后清除上次调用时间为0等待下次使用
        setting.prevTime = 0
      }, remaining)
    }
  })

  return [data, throttle.current]
}
